package com.hk.Mgr.web.controller.product;

import com.hk.base.ResponseBase;
import com.hk.commons.*;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.utils.EncryptDecryptUtils;
import com.hk.commons.utils.sys.DataHelper;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.service.order.impl.FixedAssetsOrderImpl;
import com.hk.service.order.impl.FundsOrderImpl;
import com.hk.service.order.impl.YingMiWalletImpl;
import com.hk.service.sys.ISysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.Date;

@Controller
@RequestMapping(value = "/app/allAssets")
public class HkAllAssetsCtr implements Serializable {


	/**
	 * 
	 */
	private static final long serialVersionUID = 2234725206538214815L;
	/**
	 * 
	 */
	private Logger logger = LoggerFactory
			.getLogger(HkAllAssetsCtr.class);
	@Autowired
	private ISysUser sysUserService;
	
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private YingmiApiUtils utils;

	@Autowired
	private FixedAssetsOrderImpl fixedAssetsOrderService;

	@Autowired
	private FundsOrderImpl fundsOrderService;

	@Autowired
	private YingMiWalletImpl wallet;


	@Value("${qingniu.pdf}")
	private String QN_PDF;
	
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/typeOrders", produces = "application/json;charset=UTF8", method = RequestMethod.GET)
	public ResponseBase<List<Map<String, Object>>> typeOrders(@RequestParam String userId,String curPage,String accessToken,String qryType){
		logger.info("投资详情typeOrders入参userId={},curPage={},qryType={}", userId,curPage,qryType);
		ResponseBase<List<Map<String, Object>>> resultBase=new ResponseBase<List<Map<String, Object>>>();
		if(StringHelper.isEmpty(userId)||StringHelper.isEmpty(curPage)||StringHelper.isEmpty(accessToken)){
			resultBase.setMsg(ResultCode.PARAM_LACK.getMsg());
			resultBase.setMsg(ResultCode.PARAM_LACK.getCode());
			return resultBase;
		}
		//收益都加体验金，本金都不加体验金

		//如果传入的页码小于1则显示错误
		if(Integer.parseInt(curPage) < 1 ){
			resultBase.setMsg(ResultCode.PARAM_ERROR.getMsg());
			resultBase.setMsg(ResultCode.PARAM_ERROR.getCode());
			return resultBase;
		}


        if (!EncryptDecryptUtils.checkToken(accessToken, userId)) {
			logger.info("token:{}  is not exits", accessToken);
			resultBase.setMsg(ResultCode.ILLEGAL_TOKEN.getMsg());
			resultBase.setResultCode(ResultCode.ILLEGAL_TOKEN.getCode());
			return resultBase;
		}
		try {
			Long longUserId=Long.valueOf(userId);
			SysUser user=sysUserService.findById(longUserId);
			if(user==null){
				resultBase.setMsg(ResultCode.USER_NOT_EXIST.getMsg());
				resultBase.setMsg(ResultCode.USER_NOT_EXIST.getCode());
				return resultBase;
			}			
			List<Map<String, Object>> resultList=new ArrayList();
			int pageSize=20;
			String qrySql = "select orderId,userRealName,userCardRate, prodAddRate, userPhone,dividendDate,orderTradeDate,orderCreatedOn,successAmount,dividend,productName,payBackAmt,proTerm,contractUrl,contractUrlHTML, contractTitle, proRate, extRate, extraTerm, userCardDesc,benefitType,userCardFaceValue,clearDate from orderView where payStatus = ? and confirmStatus = ? and userId = ? order by orderCreatedOn desc limit ?, ?";
			String allAssetsSql = "select (select sum(successAmount) from orderView where  payStatus = 2 and confirmStatus = ? and userId = ? and benefitType<>2 ) as sumSuccessAmount,(select sum(dividend) from orderView where payStatus=? and confirmStatus = ? and userId = ?) as sumDividend";
			Map<String, Object> allMap = null;
			List<Map<String, Object>> resultSqlList;
			Integer start = ((Integer.parseInt(curPage)-1)*pageSize);
			switch (qryType) {
			case ConstantOrderStatus.CONFIRM_STATUS__TRUE+""://持有
				allMap = this.jdbcTemplate.queryForMap(allAssetsSql, new Object[] {ConstantOrderStatus.CONFIRM_STATUS__TRUE, longUserId, ConstantOrderStatus.PAY_STATUS_TRUE, ConstantOrderStatus.CONFIRM_STATUS__TRUE, longUserId});
				resultSqlList = jdbcTemplate.queryForList(qrySql, new Object [] {ConstantOrderStatus.PAY_STATUS_TRUE, ConstantOrderStatus.CONFIRM_STATUS__TRUE, longUserId, start, pageSize});
				break;
			case ConstantOrderStatus.CONFIRM_STATUS__NO_CONFIRM+""://确认中
				allMap = this.jdbcTemplate.queryForMap(allAssetsSql, new Object[] {ConstantOrderStatus.CONFIRM_STATUS__NO_CONFIRM, longUserId, ConstantOrderStatus.PAY_STATUS_TRUE, ConstantOrderStatus.CONFIRM_STATUS__NO_CONFIRM, longUserId});
				resultSqlList = jdbcTemplate.queryForList(qrySql, new Object [] {ConstantOrderStatus.PAY_STATUS_TRUE, ConstantOrderStatus.CONFIRM_STATUS__NO_CONFIRM, longUserId, start, pageSize});
				break;
			case ConstantOrderStatus.PAY_STATUS_PAYBACK+"":	//回款
				allMap = this.jdbcTemplate.queryForMap(allAssetsSql, new Object[] {ConstantOrderStatus.CONFIRM_STATUS__PAYBACK, longUserId, ConstantOrderStatus.PAY_STATUS_PAYBACK, ConstantOrderStatus.CONFIRM_STATUS__PAYBACK, longUserId});
				resultSqlList = jdbcTemplate.queryForList(qrySql, new Object [] {ConstantOrderStatus.PAY_STATUS_PAYBACK, ConstantOrderStatus.CONFIRM_STATUS__PAYBACK, longUserId, start, pageSize});
				break;
			default:
				allMap = this.jdbcTemplate.queryForMap(allAssetsSql, new Object[] {ConstantOrderStatus.CONFIRM_STATUS__TRUE, longUserId, ConstantOrderStatus.PAY_STATUS_TRUE, ConstantOrderStatus.CONFIRM_STATUS__TRUE, longUserId});
				resultSqlList = jdbcTemplate.queryForList(qrySql, new Object [] {ConstantOrderStatus.PAY_STATUS_TRUE, ConstantOrderStatus.CONFIRM_STATUS__TRUE, longUserId, start, pageSize});
				break;
			}

			if(resultSqlList.size()>0){
				addToMap(resultSqlList,resultList,qryType,allMap);
			}
			resultBase.setMsg(ResultCode.SUCC.getMsg());
			resultBase.setMsg(ResultCode.SUCC.getCode());
			resultBase.setResult(resultList);	
			resultBase.setSize(resultList.size());
		} catch (Exception e) {
			logger.info("查询投资详情typeOrders异常,userId={}",userId);
			logger.error("<-----------------------------------error----------------------------------->",e);
			resultBase.setMsg(ResultCode.FAILED.getMsg());
			resultBase.setMsg(ResultCode.FAILED.getCode());			
		}		
		return resultBase;
	}	
	
	private void addToMap(List<Map<String, Object>> resultSqlList,List<Map<String, Object>> resultList,String qryType,Map<String, Object> allMap){
		for(Map<String, Object> map:resultSqlList){
			Map<String, Object> resultMap=new HashMap<>();
			String userRealName=(String) map.get("userRealName");
			String userPhone=(String) map.get("userPhone");
			String productName=(String) map.get("productName");					
			Long dividendDate=(Long) map.get("dividendDate");
			Long orderId=(Long) map.get("orderId");
			Long orderTradeDate=(Long) map.get("orderTradeDate");
			Long orderCreatedOn=(Long) map.get("orderCreatedOn");
			BigDecimal successAmount=(BigDecimal) map.get("successAmount");
			BigDecimal dividend=(BigDecimal) map.get("dividend");
			BigDecimal payBackAmt=(BigDecimal) map.get("payBackAmt");
			int proTerm=(int) map.get("proTerm");
			BigDecimal sumSuccessAmount=(BigDecimal) allMap.get("sumSuccessAmount");
			BigDecimal sumDividend=(BigDecimal) allMap.get("sumDividend");

			BigDecimal proRate = (BigDecimal)map.get("proRate");
			BigDecimal extRate = BigDecimal.valueOf(0.00);

			Integer extraTerm = (Integer)map.get("extraTerm");


			BigDecimal userCardRate = BigDecimal.valueOf(0.00);

			BigDecimal prodAddRate = BigDecimal.valueOf(0.00);

			//该时间 2017-11-30 00:00:00 预计清算日期为空 且小于订单时间 取预计到期日 取dividendDate 字段
			long before5Time = 1511971200000L;
            String clearDate="";
            if(map.get("clearDate") != null && map.get("dividendDate") != null) {
                String clearDateStr = map.get("clearDate").toString();
                clearDate = clearDateStr.substring(0, clearDateStr.lastIndexOf("."));

                long parseClearDate=0;
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = (Date) sdf.parse(clearDate);
                    parseClearDate = date.getTime();
                }catch (Exception e) {
                    e.printStackTrace();
                }

                if(dividendDate >= parseClearDate) {
					clearDate = DateUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss",dividendDate);
				}
            }else {
				clearDate = dividendDate==null?"":""+DateUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss",dividendDate);
			}

           /* else if(before5Time <= orderCreatedOn) {
				clearDate =  dividendDate==null?"":""+DateUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss",dividendDate);
			}*/

			if(map.get("userCardRate") != null){
				userCardRate = (BigDecimal)map.get("userCardRate");
			}


			if(map.get("prodAddRate") != null ){
				prodAddRate = (BigDecimal)map.get("prodAddRate");

			}

			//logger.info("userCardRate ={}, prodAddRate ={}", userCardRate, prodAddRate);

//			if(map.get("extRate") != null){
//				extRate = (BigDecimal)map.get("extRate");
//			}

			String userCardDesc = getUserCardDesc(map);

			String contractUrl = "";
			if(map.get("contractUrl") != null) {
				contractUrl = (String) map.get("contractUrl");
				resultMap.put("contractUrl", QN_PDF + contractUrl);
			}else{
				resultMap.put("contractUrl", null );
			}


			String contractUrlHTML = "";
			if(map.get("contractUrlHTML") != null){
				contractUrlHTML = (String )map.get("contractUrlHTML");
				resultMap.put("contractUrlHTML", QN_PDF+ contractUrlHTML );
			}else{
				resultMap.put("contractUrlHTML", null );
			}

			String contractTitle = "";
			if(map.get("contractTitle") != null){
				contractTitle = (String )map.get("contractTitle");
				resultMap.put("contractTitle", contractTitle );
			}else{
				resultMap.put("contractTitle", null);
			}


			resultMap.put("userRealName", StringHelper.isEmpty(userRealName)?"":DataUtil.getBetweenEncryptRealName(userRealName));
			resultMap.put("userPhone", StringHelper.isEmpty(userPhone)?"":DataUtil.getEncryptPhoneNum(userPhone));
			resultMap.put("productName", StringHelper.isEmpty(productName)?"":productName);
			resultMap.put("orderId",orderId);
			resultMap.put("dividendDate", dividendDate==null?"":""+DateUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss",dividendDate));
			resultMap.put("clearDate", clearDate);
			resultMap.put("orderTradeDate", orderTradeDate==null?"":""+DateUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss",orderTradeDate));
			resultMap.put("orderCreatedOn", orderCreatedOn==null?"":""+DateUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss",orderCreatedOn));
			resultMap.put("successAmount", getBigDecimal(successAmount));
			resultMap.put("dividend", getBigDecimal(dividend));
			resultMap.put("payBackAmt",getBigDecimal(payBackAmt));

			if(prodAddRate.compareTo(BigDecimal.valueOf(0.00)) == 0 ){
				resultMap.put("proRate",  DataHelper.chgBigDecimalToPrecent(proRate, 2));
			}else{
				resultMap.put("proRate",  DataHelper.chgBigDecimalToPrecent(proRate, 2) + " + " +  DataHelper.chgBigDecimalToPrecent(prodAddRate, 2) );
			}

			resultMap.put("proTerm", proTerm);
			resultMap.put("qryType",qryType);
			resultMap.put("sumSuccessAmount",getBigDecimal(sumSuccessAmount));
			resultMap.put("sumDividend",getBigDecimal(sumDividend));

			resultMap.put("userCardDesc", userCardDesc );
			resultList.add(resultMap);
		}
	}
	@ResponseBody
	@RequestMapping(value = "/allData", produces = "application/json;charset=UTF8", method = RequestMethod.GET)
	public Map<String, Object> qryHkAllAssets(
			@RequestParam String userId,String phone,String accountId) {

		logger.info("qryHkAllAssets userId ={}, phone ={}, accountId={}", userId, phone, accountId);
		Map<String, Object> resultMap=new HashMap<>();



		Callable<Map<String, Object>> fixOrderCallable = fixedAssetsOrderService;
		fixedAssetsOrderService.setUserId(Long.valueOf(userId));



		FutureTask<Map<String, Object>> fixOrderTask = new FutureTask<>(fixOrderCallable);


		Callable<Map<String, Object>> fundOrderCallable = fundsOrderService;
		fundsOrderService.setPhonenum(phone);
		fundsOrderService.setAccountId(accountId);
		fundsOrderService.setUserId(userId);

		FutureTask<Map<String, Object>> fundOrderTask = new FutureTask<>(fundOrderCallable);

		Callable<Map<String,Object>> walletCallable = wallet;
		wallet.setAccountId(accountId);
		wallet.setBrokerUserId(phone);
		FutureTask<Map<String, Object>> walletTask = new FutureTask<>(walletCallable);




		new Thread(fixOrderTask).start();
		new Thread(fundOrderTask).start();
		new Thread(walletTask).start();


		// 调用get()阻塞主线程，反之，线程不会阻塞
		try {
			Map<String, Object> fixOrderMsgMap = fixOrderTask.get();
			resultMap.put("fixedAssets", fixOrderMsgMap);
		} catch (Exception e) {
			logger.error("get FixedAssetsOrderMsg error "  + e) ;
		}


		// 调用get()阻塞主线程，反之，线程不会阻塞
		try {
			Map<String, Object> fundOrderMsgMap  = fundOrderTask.get();
			resultMap.put("funds", fundOrderMsgMap);
		} catch (Exception e) {
			logger.error("get fundOrderMsg error "  + e) ;
		}

		// 调用get()阻塞主线程，反之，线程不会阻塞
		try {
			Map<String, Object> walletMsgMap  = walletTask.get();
			resultMap.put("wallets", walletMsgMap);
		} catch (Exception e) {
			logger.error("get walletMsgMap error "  + e) ;
		}
		return  resultMap;

	}

	/**
	 * 根据不对卡券类型设置卡券描述
	 * @param map
	 * @return
	 */
	private String getUserCardDesc(Map<String, Object> map){
		String result = "未加息";
		if(map.get("userCardRate") == null)
			return result;

		BigDecimal userCardRate = (BigDecimal)map.get("userCardRate");
		if(userCardRate.compareTo(BigDecimal.valueOf(0.0000)) ==0)
			return result;

		String cardType = String.valueOf(map.get("benefitType"));
		Integer extraTerm = (Integer)map.get("extraTerm");
		int proTerm=(int) map.get("proTerm");
		BigDecimal userCardFaceValue =(BigDecimal)map.get("userCardFaceValue");
		if(extraTerm !=null && extraTerm !=0){
			proTerm = extraTerm;
		}

		if(CouponType.RAISE_RATES.getCode().equals(cardType)){
			result = DataHelper.chgBigDecimalToPrecent(userCardRate, 1) + "加息(" + proTerm + "天)";
		}else if(CouponType.VOUCHER_COUPON.getCode().equals(cardType)){
			result  = userCardFaceValue.setScale(0).toString()+"元加息("+proTerm+"天)";
		}else{
			result = DataHelper.chgBigDecimalToPrecent(userCardRate, 1) + "加息(" + proTerm + "天)";
		}

		return result;
	}

	public String qryLeijiShouyi(String phone,String accountId, String fundCodes) {
		// trade/getProfits
		Map<String, String> params = new HashMap<>();
		params.put("brokerUserId", phone);// PayMentMethodCtrl
		params.put("accountId", accountId);
		params.put("beginDate", "2016-01-01");
		Calendar calendar = Calendar.getInstance();
		String endDate = calendar.get(Calendar.YEAR)
				+ "-"
				+ ((calendar.get(Calendar.MONTH) + 1) > 9 ? (calendar
						.get(Calendar.MONTH) + 1) : ("0" + (calendar
						.get(Calendar.MONTH) + 1))) + "-"
				+ calendar.get(Calendar.DAY_OF_MONTH);
		params.put("endDate", endDate);
		if (!StringHelper.isEmpty(fundCodes)) {
			params.put("fundCode", fundCodes);
		}
		String shouyi = utils.get("/trade/getProfits", params);
		return shouyi;
	}
		

	private BigDecimal getBigDecimal(BigDecimal old) {
		return old == null ? new BigDecimal(0) : old;
	}


}
